﻿using System;
using System.Collections.Generic;
using System.Web;
using umbraco.cms.presentation.Trees;
using System.Xml;

namespace TwentyTree4Umbraco.Trees
{
    public class LoadTwentyTree : BaseTree
    {
        public LoadTwentyTree(string application) :
            base(application) { }


        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
            rootNode.Icon = FolderIcon;
            rootNode.OpenIcon = FolderIconOpen;
            rootNode.NodeType = TreeAlias;
            rootNode.NodeID = "init";
        }

        protected override void CreateRootNodeActions(ref List<umbraco.interfaces.IAction> actions)
        {
            actions = new List<umbraco.interfaces.IAction>();
        }

        protected override void CreateAllowedActions(ref List<umbraco.interfaces.IAction> actions)
        {
            actions = new List<umbraco.interfaces.IAction>();
        }

        public override void Render(ref XmlTree tree)
        {
            int c = 0;
            foreach (XmlNode page in Config.GetPages())
            {
                XmlTreeNode xNode = XmlTreeNode.Create(this);
                xNode.NodeID = c.ToString();
                xNode.Text = page.Attributes["name"].Value;
                xNode.Icon = FolderIcon;
                xNode.Action = "javascript:openTwentyTreePage('" + page.Attributes["url"].Value + "')";
                tree.Add(xNode);

                c++;
            }

        }

        public override void RenderJS(ref System.Text.StringBuilder Javascript)
        {
            Javascript.Append(
                    "function openTwentyTreePage(page){");
            Javascript.Append(
                "parent.right.document.location.href = 'http://" + Config.GetSetting("domain") + "' + page;");
            Javascript.Append(
                "}");
        }
    }
}
